import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_app/2_advance/net/app_api.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

import 'app_response_entity.dart';

late final Dio _appDio;

const int _connectTimeout = 10000; // 10s
const int _receiveTimeout = 10000; // 10s

class AppHttp {
  static init() {
    _appDio = Dio()
      ..options = BaseOptions(
        connectTimeout: _connectTimeout,
        receiveTimeout: _receiveTimeout,
        baseUrl: AppApi.baseUrl,
        // contentType: Headers.formUrlEncodedContentType, // 可设置为表单
        contentType: Headers.jsonContentType,
      )
      // 拦截器感觉只需要日志、token等
      ..interceptors.addAll([
        // FileCacheStore(directory),
        // 日志
        PrettyDioLogger(requestBody: true),
        // 网络错误
        // InterceptorsWrapper(onResponse: (response, handler) {
        //   if (response.data['data'] == null) {
        //     response.data['data'] = jsonDecode('{}');
        //   }
        //   handler.next(response);
        // }, onRequest: (request, handler) {
        //   request.headers['token'] = '';
        //   handler.next(request);
        // }),
      ]);
  }

  static Future<T?> request<T>({
    required AppHttpMethod method,
    required String path,
    Map<String, dynamic>? queryParameters,
    dynamic data,
  }) async {
    try {
      var resultData = jsonDecode('{}');
      switch (method) {
        case AppHttpMethod.GET:
          resultData = (await _appDio.get(path, queryParameters: queryParameters)).data;
          break;
        case AppHttpMethod.POST:
          resultData = (await _appDio.post(path, data: data, queryParameters: queryParameters)).data;
          break;
      }
      AppResponseEntity responseEntity = AppResponseEntity.fromJson(resultData);
      // 可以增加返回code的判断
      return responseEntity.data;
    } on DioError catch (e) {
      // 这里只是打印，一般要做其他操作，比如显示到UI上e
      // 用GETX可能比较好
      // 以下错误都可以称为网络错误
      switch (e.type) {
        // incorrect status, such as 404, 503
        case DioErrorType.response:
          print('网络错误: ${e.message}');
          break;
        case DioErrorType.connectTimeout:
          break;
        case DioErrorType.sendTimeout:
          break;
        case DioErrorType.receiveTimeout:
          break;
        case DioErrorType.cancel:
          break;
        case DioErrorType.other:
          break;
      }
      return null;
    }
    catch (e) {
      // 其他报错：比如解析数据
      return null;
    }
  }

}

enum AppHttpMethod {
  GET,
  POST,
}